﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Interop.jmail;
using UDS.Entity;

namespace UDS.Components
{
    /// <summary>
    /// Mail处理类
    /// </summary>
    public class MailClass
    {
        #region 获取某用户的某信箱中的信件 返回DataTable

        /// <summary>
        ///获取某邮箱中的信件 返回DataTable
        /// </summary>
        /// <param name="Username">用户名</param>
        /// <param name="FolderType">邮箱类型</param>
        public DataTable GetMails(int FolderType, string Username)
        {
            var data = new Database();
            var parameters = new[]
            {
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 20, Username),
                Database.MakeInParam("@MailFolderType", SqlDbType.Int, 8, FolderType)
            };
            try
            {
                using (SqlDataReader dataReader = data.RunDataReader("dbo.sproc_MailGetBriefInfo", parameters))
                {
                    return Tools.ConvertDataReaderToDataTable(dataReader);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString());
                return null;
            }
        }

        #endregion

        #region 获取某项目中的信件 返回DataTable

        /// <summary>
        ///获取某项目中的信件 返回DataTable
        /// </summary>
        /// <param name="ClassID">项目ID</param>
        /// <param name="Username">The name of a user.</param>
        public DataTable GetClassMails(int ClassID, string Username)
        {
            var data = new Database();
            const int MailFolderType = 1;

            var parameters = new[]
            {
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 20, Username),
                Database.MakeInParam("@ClassID", SqlDbType.Int, 20, ClassID),
                Database.MakeInParam("@MailFolderType", SqlDbType.Int, 3, MailFolderType)
            };
            try
            {
                using (SqlDataReader dataReader = data.RunDataReader("dbo.sproc_MailInClassGetBriefInfo", parameters))
                {
                    return Tools.ConvertDataReaderToDataTable(dataReader);
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString());
                return null;
            }
        }

        #endregion

        #region 获取某用户的某信箱中的信件 返回SqlDataReader

        /// <summary>
        ///获取某邮箱中的信件 返回SqlDataReader
        /// </summary>
        /// <param name="Username">用户名</param>
        /// <param name="FolderType">邮箱类型</param>
        public SqlDataReader GetMailsDbReader(int FolderType, string Username)
        {
            var data = new Database();
            var parameters = new[]
            {
                Database.MakeInParam("@Username", SqlDbType.NVarChar, 20, Username),
                Database.MakeInParam("@MailFolderType", SqlDbType.Int, 8, FolderType)
            };
            try
            {
                return data.RunDataReader("dbo.sproc_MailGetBriefInfo", parameters);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString());
                return null;
            }
        }

        #endregion

        #region 将一组邮件移至指定信箱

        /// <summary>
        /// 将一组邮件移至指定信箱
        /// </summary>
        /// <param name="FolderType">The type of a mail folder.</param>
        /// <param name="MailIDStr">邮件ID的连接字符串，用逗号相隔开</param>
        public bool MailRemove(int FolderType, string MailIDStr)
        {
            var data = new Database();
            var parameters = new[]
            {
                Database.MakeInParam("@FolderType", SqlDbType.Int, 20, FolderType),
                Database.MakeInParam("@MailIDStr", SqlDbType.NVarChar, 4000, MailIDStr)
            };
            try
            {
                data.RunProc("dbo.sproc_MailRemove", parameters);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString());
                return false;
            }
        }

        #endregion

#if false
        #region 邮件主体发送

        /// <summary>
        /// 发送邮件，只包括数据库操作
        /// </summary>
        /// <param name="mailbody">Mail类</param>
        private static int Send(MailMainBody mailbody)
        {
            var parameters = new[]
            {
                Database.MakeInParam("@MailFolderType", SqlDbType.Int, 20, mailbody.MailFolderType),
                Database.MakeInParam("@MailReceiverStr", SqlDbType.NVarChar, 300, mailbody.MailReceiverStr),
                Database.MakeInParam("@MailSendDate", SqlDbType.DateTime, 20, mailbody.MailSendDate),
                Database.MakeInParam("@MailSendLevel", SqlDbType.SmallInt, 20, mailbody.MailSendLevel),
                Database.MakeInParam("@MailSender", SqlDbType.NVarChar, 20, mailbody.MailSender),
                Database.MakeInParam("@MailReceiver", SqlDbType.NVarChar, 20, mailbody.MailReceiver),
                Database.MakeInParam("@MailSubject", SqlDbType.NVarChar, 50, mailbody.MailSubject),
                Database.MakeInParam("@MailBody", SqlDbType.Text, 300000, mailbody.MailBody),
                Database.MakeInParam("@MailCcToAddr", SqlDbType.NVarChar, 300, mailbody.MailCcToAddr),
                Database.MakeInParam("@MailBccToAddr", SqlDbType.NVarChar, 300, mailbody.MailBccToAddr),
                Database.MakeInParam("@MailReadFlag", SqlDbType.Bit, 1, mailbody.MailReadFlag),
                Database.MakeInParam("@MailTypeFlag", SqlDbType.Bit, 1, mailbody.MailTypeFlag),
                Database.MakeInParam("@MailClassID", SqlDbType.Int, 1, mailbody.MailClassID),
                Database.MakeInParam("@MailImportance", SqlDbType.Int, 1, mailbody.MailImportance),
                Database.MakeOutParam("@MailID", SqlDbType.Int, 20)
            };

            using (var db = new Database())
            {
                db.RunProc("dbo.sproc_MailSend", parameters);

                SqlParameter p = parameters[parameters.Length - 1];
                if (p.Value == DBNull.Value)
                {
                    return -1;
                }
                return (int)p.Value;
            }
        }

        #endregion

        #region 发送一组邮件

        /// <summary>
        /// 只需传入一个MailMainBody对象，会自动拆分ReceiverStr,逐个发送
        /// </summary>
        /// <param name="mailbody">MailMainBody类的一个实例，用来进行参数传递</param>
        /// <returns>返回邮件ID数组</returns>
        public static IList<int> MailSend(MailMainBody mailbody)
        {
            string[] receiverList = Utility.MergeArray(
                StringComparer.InvariantCultureIgnoreCase,
                Utility.SplitArray(mailbody.MailReceiverStr),
                Utility.SplitArray(mailbody.MailCcToAddr),
                Utility.SplitArray(mailbody.MailBccToAddr));
            var list = new List<int>();

            // 发送一封邮件至发件人发件箱
            mailbody.MailFolderType = UDS.Entity.MailFolderType.Outbox;
            mailbody.MailReceiver = mailbody.MailSender;
            list.Add(Send(mailbody));

            // 开始循环发送邮件
            foreach (string receiver in receiverList)
            {
                mailbody.MailFolderType = MailFolderType.Index; //收件箱
                mailbody.MailReceiver = receiver;

                int mailId = Send(mailbody);
                if (mailId > 0)
                {
                    list.Add(mailId);
                }
            }
            return list;
        }

        #endregion
#endif

        #region 邮件附件数据库操作

        /// <summary>
        /// 发送邮件附件，只包括数据库操作
        /// </summary>
        /// <param name="att">MailAttachFile类</param>
        /// <param name="MailID">邮件ID</param>
        public void AttSend(MailAttachFile att, int MailID)
        {
            var data = new Database();
            var parameters = new[]
            {
                Database.MakeInParam("@MailID", SqlDbType.Int, 20, MailID),
                Database.MakeInParam("@FileName", SqlDbType.NVarChar, 300, att.FileName),
                Database.MakeInParam("@FileSize", SqlDbType.Int, 20, att.FileSize),
                Database.MakeInParam("@FileAttribute", SqlDbType.SmallInt, 20, att.FileAttribute),
                Database.MakeInParam("@FileVisualPath", SqlDbType.NVarChar, 200, att.FileVisualPath),
                Database.MakeInParam("@FileAuthor", SqlDbType.NVarChar, 50, att.FileAuthor),
                Database.MakeInParam("@FileCatlog", SqlDbType.NVarChar, 20, att.FileCatlog)
            };
            try
            {
                data.RunProc("dbo.sproc_AddMailAttFile", parameters);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString());
                throw new Exception("邮件附件发送出错!", ex);
            }
        }

        #endregion

        #region 获取邮件附件的内容

        /// <summary>
        /// Get  sqldatareader  from TabMailAttFiles
        /// </summary>
        public SqlDataReader GetMailAttInfoDbreader(string MailID)
        {
            // create data object and params
            var data = new Database();
            var parameters = new[]
            {
                Database.MakeInParam("@MailID", SqlDbType.NVarChar, 100, MailID)
            };


            try
            {
                // run the stored procedure
                return data.RunDataReader("dbo.sproc_MailGetAttachFilesInfo", parameters);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString());
                throw new Exception("邮件读取出错!", ex);
            }
        }

        #endregion

        #region 根据邮件ID字符串获取邮件附件的内容

        /// <summary>
        /// Get  sqldatareader  from TabMailAttFiles
        /// </summary>
        public SqlDataReader GetMailAttInfoByMailIDDbreader(string FileIDStr)
        {
            // create data object and params
            var data = new Database();
            var parameters = new[]
            {
                Database.MakeInParam("@FileIDStr", SqlDbType.NVarChar, 4000, FileIDStr)
            };


            try
            {
                // run the stored procedure
                return data.RunDataReader("dbo.sproc_MailGetAttachFilesInfoByMailID", parameters);
            }
            catch (Exception ex)
            {
                Logger.Log(ex.ToString());
                throw new Exception("邮件读取出错!", ex);
            }
        }

        #endregion

        
    }
}